<template>
  <view class="content">
    <uni-search-bar placeholder="请输入要搜索的内容" class="uni-searchbar" cancelButton="none" radius="50%"
                    @confirm="search"
                    @clear="clearKeyWord">
    </uni-search-bar>
    <view v-if="blogs.length==0" class="none">
      <image class="logo" src="/static/icons/nodata.png" mode="widthFix"></image>
      <text>抱歉，没有相关资源</text>
    </view>

    <view v-else class="item-container" v-for="(item,index) in blogs" :key="item.id" @click="gotoDetail(item.id)">
      <text class="item-title">{{ item.title }}</text>
      <rich-text :nodes="item.description" class="item-desc"></rich-text>
      <image :src="item.picture" mode="widthFix" class="img item-pic"></image>
      <text class="iconfont icon-xia img-oper" @click.stop="popSheet(item.id)"></text>
      <view>
        <text v-for="(tag,idx) in  item.tags" :key="idx" class="item-tag">{{ tag }}</text>
      </view>
      <image :src="item.user.avatar" mode="aspectFill" class="img-head" @click.stop="showInfo(item.user)"></image>

      <view class="icon-container">
        <image @click.stop="changeGood(item.id,true)" v-if="good_ids.indexOf(item.id)<0"
               class="iconfont icon-dianzan icon"></image>
        <image @click.stop="changeGood(item.id,false)" v-else class="iconfont icon-yidongduan_yidianzan icon">
        </image>
        <text class="icon-text">{{ item.good }}</text>
        <image class="iconfont icon-pinglun icon"></image>
        <text class="icon-text">{{ item.comments.length }}</text>
        <image class="iconfont icon-icon- icon"></image>
        <text class="icon-text">{{ item.readCount }}</text>
      </view>
    </view>
    <view class="bottom" v-if="blogs.length==count">
      -----我是有底线的-----
    </view>
<!--    <dialog-shell ref="shell" title="哈哈哈哈">-->
<!--		<text>好好好好好好好</text>-->
<!--	</dialog-shell>-->
    <dialog-shell ref="shell" title="个人信息">
		 <text style="padding: 10rpx;font-size: 26rpx">{{userInfo}}</text>
	</dialog-shell>
  </view>
</template>
<script>
let page = 0
let size = 5
let key_blogs = "blogs"
export default {
  data() {
    return {
      blogs: [],
      count: -1,
      searching: false,
      good_ids: [],
      userInfo:''
    }
  },
  onLoad() {
    // 页面加载注册
    this.$noti.add(this.$params.noti_refresh_count,this.notifyRefreshCount,this)
    this.$noti.add(this.$params.key_good_ids,this.notifyRefreshGoodCount,this)
    this.$noti.add(this.$params.noti_comment_count,this.notifyRefreshCmtCount,this)

    // let blogs = uni.getStorageSync(key_blogs)
    let blogs = uni.getStorageSync(key_blogs)
    let goods = uni.getStorageSync(this.$params.key_good_ids)
    if (blogs) {
      this.blogs = blogs
      this.count = blogs.length
      this.good_ids=goods
    } else {
      this.getPageBlogs()
    }
    let ids = uni.getStorageSync(this.$params.key_good_ids)

  },
  onUnload(){
    // 移除通知
    this.$noti.remove(this.$params.noti_refresh_count,this)
    this.$noti.remove(this.$params.noti_good_count,this)
  },
  // 监听下拉动作
  onPullDownRefresh() {
    page = 0
    this.blogs = []
    this.count = -1
    this.getPageBlogs()

  },
  // 页面滚动到底部的事件
  onReachBottom() {
    // if (this.blogs.length == this.count) {
    // 	console.log("test");
    // 	return
    // }
    page += 1
    this.getPageBlogs()
    // console.log("拉");
  },
  methods: {
    gotoDetail(id) {
      uni.navigateTo({
        url: '../blog/blog?id=' + id,
        success: res => {
        },
        fail: () => {
        },
        complete: () => {
        }
      })
    },
    //通知中心同步点赞数
    notifyRefreshGoodCount(info) {
      let id = info.id
      let good = info.goodCount
      this.refreshGoodCount(id, good);
    },
    //通知中心和页面通讯更新点赞数
    refreshGoodCount(id, good) {
      this.good_ids = uni.getStorageSync(this.$params.key_good_ids);
      this.blogs.forEach(blog => {
        if (blog.id == id) {
          blog.good = good
        }
      })
    },
    // 通知刷新次数
    notifyRefreshCount(info){
      let id=info.id
      let count=info.count
      this.refreshReadCount(id,count)
    },
    // 刷新读取次数
    refreshReadCount(id, count) {
      this.blogs.forEach(b => {
        if (b.id == id) {
          b.readCount = count
        }
      })
    },
  //通知刷新评论数
    notifyRefreshCmtCount(info){
      this.blogs.forEach(blog =>{
        if(blog.id==info.id){
          blog.comments = info.comments;
        }
      })
    },



    //点赞方法
    changeGood(id, isGood) {

      //TODO:同步到服务器，并且取得最新数据
      let url = this.$params.host
      let action = isGood ? this.$params.action_good : this.$params.action_del_good
      url += action
      let data = {
        "id": id
      }
      this.$request.postParam(url, data, res => {
        this.blogs.forEach(blog => {
          if (blog.id == id) {
            blog.good = res.data
          }
        })
        if (isGood) {
          // this.good_ids.push(id)
          this.good_ids = this.good_ids.concat(id)
        } else {
          let index = this.good_ids.indexOf(id)
          this.$util.remove(this.good_ids, index)
        }
        uni.setStorageSync(this.$params.key_good_ids, this.good_ids)
      }, () => {
      })
    },
    getPageBlogs() {
      if (this.blogs.length == this.count) {
        uni.showToast({
          title: "已经全部加载完成了噢",
          icon: 'none'
        })
        return
      }
      let header = {
        "content-type": "application/json;charset=UTF-8",
        "page": page,
        "size": size

      }
      this.$request.getWithHeader(this.$params.host + this.$params.action_blogs_page, header, res => {
            res.data.forEach(blog => {
              if (!blog.picture.startsWith("http")) {
                blog.picture = this.$params.host + blog.picture
              }
              blog.user.avatar = this.$params.host + blog.user.avatar
            })
            this.blogs = [...this.blogs, ...res.data]
            console.log(res)
            this.count = parseInt(res.message)
            uni.setStorageSync(key_blogs, this.blogs)
          },
          () => {

            uni.stopPullDownRefresh()

          })

    },
    search(e) {
      let kw = e.value
      if (kw.length > 0) {
        this.blogs = []
        //重置count
        this.count = -1
        //发送请求：1.要在常量文件中添加搜索地址 2.使用get方法发起请求 3.请求的结果要处理
        let url = this.$params.host + this.$params.action_search + kw
        this.$request.get(url, res => {
          res.data.forEach(blog => {
            if (!blog.picture.startsWith("http")) {
              blog.picture = this.$params.host + blog.picture
            }
            blog.user.avatar = this.$params.host + blog.user.avatar
          })
          this.blogs = [...this.blogs, ...res.data]

        }, () => {
          this.searching = true
        })


      }
    },
    // 清除关键词
    clearKeyWord() {
      this.blogs = []
      page = 0
      this.getPageBlogs()
      this.searching = false
    },

    popSheet(id) {
      uni.showActionSheet({
        itemList: ['删除', '收藏'],
        success: res => {
          if (res.tapIndex == 0) {
            uni.showModal({
              title: '删除blog',
              content: '确认删除？',
              showCancel: false,
              cancelText: '删除',
              success: res => {
                if (res.confirm) {
                  this.deleteBlog(id)
                }
              },
              fail: () => {

              },
              complete: () => {

              }
            });
          } else {
            uni.showToast({
              title: '收藏成功'
            })
          }
        },
        fail: () => {

        },
        complete: () => {

        }
      })
    },
    deleteBlog(id) {
      uni.showToast({
        title: '未登录不能进行操作'
      })
    },
    showInfo(user){
      this.userInfo="作者："+user.nickName+"\n练系方式"+user.email
      this.$refs.shell.show();
    }
  }
}
</script>

<style>
@import url("index.css");
</style>
